#! /usr/bin/env python

import os
import re
import sys

rootRe = re.compile("Kokkos(.*?)_eti_spec_inst_(.*?)[.]cpp")
cppReplRe = re.compile("namespace Impl {\n(.*)", re.DOTALL)
ifdefReplRe = re.compile("#if defined(.*?)#include", re.DOTALL)

def walker(topdir, dirname, files):
  os.chdir(dirname)
  for f in files:
    match = rootRe.search(f)
    if not match:
      print("Bad file %s" % f)
      continue
    fxn, types = match.groups()
    newPath = "Kokkos%s_eti_spec_inst.cpp.in" % fxn
    if f.endswith("cpp") and not os.path.isfile(newPath):
      text = open(f).read()
      repl = "namespace Impl {\n@%s_ETI_INST_BLOCK@\n  } //IMPL \n} //Kokkos" % fxn.upper()
      newText = cppReplRe.sub(repl, text)
      newText = ifdefReplRe.sub("#include", newText)
      cmd = "git mv %s %s" % (f, newPath)
      print("%s : %s" % (os.getcwd(), cmd))
      os.system(cmd)
      open(newPath, "w").write(newText)
    else:
      cmd = "git rm %s" % f
      print("%s : %s" % (os.getcwd(), cmd))
      os.system(cmd)
  os.chdir(topdir)

os.path.walk(".", walker, os.getcwd())

